package controllers

import (
	"api/models"
	beego "github.com/beego/beego/v2/server/web"
	"log"
)

type GoodsController struct {
	beego.Controller
}

func (c *GoodsController) Add() {

	title := c.GetString("title")
	content := c.GetString("content")
	if title == "" || content == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "菜品名称或者内容为空",
		}
		c.ServeJSON()
		return
	}

	f, h, err := c.GetFile("picture")
	if err != nil {
		log.Fatal("picture upload  err ", err)
	}
	defer f.Close()

	if h.Size > 1024*1024*2 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "菜品图片不能超过2M",
		}
		c.ServeJSON()
		return
	}
	uploadPath := "static/img/" + h.Filename
	c.SaveToFile("picture", uploadPath)

	picturePath := "http://127.0.0.1:8080/" + uploadPath

	Good := models.Good{
		Title:   title,
		Content: content,
		Picture: picturePath,
	}
	models.DB.Table("goods").Create(&Good)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}
